package com.zq.多线程设计模式.多线程打印奇偶数;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Jiu
 * @description：
 * @date 2021/04/07   9:36
 **/
public class TwoThread {

    private int start = 0;

    /*
    * 保证内存可见性
    * 用所以后用不用volatile 一样
    * */
    private  boolean flag =false;

    /*
    * 可重入锁
    * */
    private static final Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        TwoThread twoThread = new TwoThread();
        Thread t1 = new Thread(new OuNumber(twoThread));
        t1.setName("t11111");
        Thread t2 = new Thread(new JiNumber(twoThread));
        t2.setName("p00000");

        t1.start();
        t2.start();

    }


    public static class OuNumber implements Runnable {

        private TwoThread twoThread;

        public OuNumber(TwoThread twoThread) {
            this.twoThread = twoThread;
        }

        @Override
        public void run() {

            while (twoThread.start<=100){
                if (twoThread.flag){
                    lock.lock();
                    try {
                        System.out.println(Thread.currentThread().getName()+"+++++"+twoThread.start);
                        twoThread.start++;
                        twoThread.flag = false;
                    } finally {
                        lock.unlock();
                    }
                }else {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }


    }
    public static class JiNumber implements Runnable {

        private TwoThread twoThread;

        public JiNumber(TwoThread twoThread) {
            this.twoThread = twoThread;
        }

        @Override
        public void run() {
            while (twoThread.start <= 100){
                if (!twoThread.flag){
                    lock.lock();
                    try {
                        System.out.println(Thread.currentThread().getName()+"------------"+twoThread.start);
                        twoThread.start++;
                        twoThread.flag = true;
                    } finally {
                        lock.unlock();
                    }
                }else {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }
    }

}
